<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  
  <title>redis分布式锁 | JAVA</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="缓存">
  
  
  
  
  <meta name="description" content="分布式锁什么是分布式锁?分布式锁就是控制分布式系统或不同系统之间共同访问共享资源的一种锁实现,如果不同的系统或同一个系统的不同主机之间共享了某个资源时，往往需要互斥来防止彼此干扰来保证一致性。 分布式锁需要具备哪些条件 互斥性:在任意一个时刻,只有一个客户端持有锁 无死锁:即便持有锁的客户端崩溃或者其他意外事件,锁仍然可以被获取。 容错:只要大部分redis节点都活着,客户端就可以获取锁和释放锁">
<meta name="keywords" content="缓存">
<meta property="og:type" content="article">
<meta property="og:title" content="redis分布式锁">
<meta property="og:url" content="https://jameslin23.gitee.io/2020/12/07/redis分布式锁/index.html">
<meta property="og:site_name" content="JAVA">
<meta property="og:description" content="分布式锁什么是分布式锁?分布式锁就是控制分布式系统或不同系统之间共同访问共享资源的一种锁实现,如果不同的系统或同一个系统的不同主机之间共享了某个资源时，往往需要互斥来防止彼此干扰来保证一致性。 分布式锁需要具备哪些条件 互斥性:在任意一个时刻,只有一个客户端持有锁 无死锁:即便持有锁的客户端崩溃或者其他意外事件,锁仍然可以被获取。 容错:只要大部分redis节点都活着,客户端就可以获取锁和释放锁">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/image-20201207205319341.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/image-20201207210005131.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/1090617-20190618183025891-1248337684.jpg">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/1090617-20190618183037704-975536201.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/1090617-20190618183046827-1994396879.png">
<meta property="og:updated_time" content="2020-12-09T02:23:36.865Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="redis分布式锁">
<meta name="twitter:description" content="分布式锁什么是分布式锁?分布式锁就是控制分布式系统或不同系统之间共同访问共享资源的一种锁实现,如果不同的系统或同一个系统的不同主机之间共享了某个资源时，往往需要互斥来防止彼此干扰来保证一致性。 分布式锁需要具备哪些条件 互斥性:在任意一个时刻,只有一个客户端持有锁 无死锁:即便持有锁的客户端崩溃或者其他意外事件,锁仍然可以被获取。 容错:只要大部分redis节点都活着,客户端就可以获取锁和释放锁">
<meta name="twitter:image" content="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/image-20201207205319341.png">
  
    <link rel="alternate" href="/atom.xml" title="JAVA" type="application/atom+xml">
  

  

  <link rel="icon" href="/css/images/mylogo.jpg">
  <link rel="apple-touch-icon" href="/css/images/mylogo.jpg">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt; src:url("/css/fonts/FuturaPTBold.otf") format("woff");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt-light; src:url("/css/fonts/FuturaPTBook.otf") format("woff");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt-italic; src:url("/css/fonts/FuturaPTBookOblique.otf") format("woff");font-weight:400;font-style:italic;}
}

  </style>
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>
  <script src="/js/bootstrap.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css">

  
    <link rel="stylesheet" href="/css/dialog.css">
  

  

  
    <link rel="stylesheet" href="/css/header-post.css">
  

  
  
  
    <link rel="stylesheet" href="/css/vdonate.css">
  

</head>
</html>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  
  <div id="container">
    <div id="wrap">
      
        <header>

    <div id="allheader" class="navbar navbar-default navbar-static-top" role="navigation">
        <div class="navbar-inner">
          
          <div class="container"> 
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>

            
              <a class="brand" style="border-width: 0;">
                <p>JAVA</p>
              </a>
            
            
            <div class="navbar-collapse collapse">
              <ul class="hnav navbar-nav">
                
                  <li> <a class="main-nav-link" href="/">首页</a> </li>
                
                  <li> <a class="main-nav-link" href="/archives">归档</a> </li>
                
                  <li> <a class="main-nav-link" href="/categories">分类</a> </li>
                
                  <li> <a class="main-nav-link" href="/tags">标签</a> </li>
                
                  <li> <a class="main-nav-link" href="/about">关于</a> </li>
                
                  <li><div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder>
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="请输入关键词...">
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(无标题)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div></li>
            </ul></div>
          </div>
                
      </div>
    </div>

</header>



      
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-redis分布式锁" style="width: 75%; float:left;" class="article article-type-post" itemscope itemprop="blogPost">
  <div id="articleInner" class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" itemprop="name">
      redis分布式锁
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	<a href="/2020/12/07/redis分布式锁/" class="article-date">
	  <time datetime="2020-12-07T12:01:38.000Z" itemprop="datePublished">2020-12-07</time>
	</a>

      
    <a class="article-category-link" href="/categories/Nosql/">Nosql</a>

      
	<a class="article-views">
	<span id="busuanzi_container_page_pv">
		阅读量<span id="busuanzi_value_page_pv"></span>
	</span>
	</a>

      

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <h1 id="分布式锁"><a href="#分布式锁" class="headerlink" title="分布式锁"></a>分布式锁</h1><h2 id="什么是分布式锁"><a href="#什么是分布式锁" class="headerlink" title="什么是分布式锁?"></a>什么是分布式锁?</h2><p>分布式锁就是控制分布式系统或不同系统之间共同访问共享资源的一种锁实现,如果不同的系统或同一个系统的不同主机之间共享了某个资源时，往往需要互斥来防止彼此干扰来保证一致性。</p>
<h2 id="分布式锁需要具备哪些条件"><a href="#分布式锁需要具备哪些条件" class="headerlink" title="分布式锁需要具备哪些条件"></a>分布式锁需要具备哪些条件</h2><ol>
<li><strong>互斥性</strong>:在任意一个时刻,只有一个客户端持有锁</li>
<li><strong>无死锁</strong>:即便持有锁的客户端崩溃或者其他意外事件,锁仍然可以被获取。</li>
<li><strong>容错</strong>:只要大部分redis节点都活着,客户端就可以获取锁和释放锁</li>
</ol>
<h2 id="分布式锁实现有哪些？"><a href="#分布式锁实现有哪些？" class="headerlink" title="分布式锁实现有哪些？"></a>分布式锁实现有哪些？</h2><ul>
<li><strong>数据库</strong></li>
<li><strong>Memcached（add命令）</strong></li>
<li><strong>Redis（setnx命令）</strong></li>
<li><strong>Zookeeper（临时节点）</strong></li>
</ul>
<h1 id="分布式锁实现"><a href="#分布式锁实现" class="headerlink" title="分布式锁实现"></a>分布式锁实现</h1><h2 id="SET-key-value-NX"><a href="#SET-key-value-NX" class="headerlink" title="SET key value NX"></a>SET key value NX</h2><p>假设有两个客户端A和B，A获取到分布式的锁。A执行了一会，突然A所在的服务器断电了（或者其他什么的），也就是客户端A挂了。这时出现一个问题，这个锁一直存在，且不会被释放，其他客户端永远获取不到锁。如下示意图</p>
<p><img src="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/image-20201207205319341.png" alt="image-20201207205319341"></p>
<h2 id="SET-lockKey-value-NX-EX-30"><a href="#SET-lockKey-value-NX-EX-30" class="headerlink" title="SET lockKey value NX EX 30"></a>SET lockKey value NX EX 30</h2><p><strong>注: 要保证设置过期时间和设置锁具有原子性</strong></p>
<p>此时又出现一个问题,过程如下</p>
<ol>
<li>客户端A获取锁成功,过期时间30秒</li>
<li>客户端A在某个程序上阻塞了50秒</li>
<li>30秒时间到了，锁自动释放了</li>
<li>客户端B获取对应同一资源的锁</li>
<li>客户端A从阻塞恢复过来,释放掉了客户端B持有的锁</li>
</ol>
<p><img src="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/image-20201207210005131.png" alt="image-20201207210005131"></p>
<p>这时会有两个问题</p>
<ol>
<li>过期时间如何保证大于业务执行时间?</li>
<li>如何保证锁不会被误删除?</li>
</ol>
<p><strong>先来解决如何保证锁不会被误删除这个问题。 这个问题可以通过设置value为当前客户端生成的一个随机字符串，且保证在足够长的一段时间内在所有客户端的所有获取锁的请求中都是唯一的。</strong></p>
<h2 id="lua脚本释放锁具备原子性"><a href="#lua脚本释放锁具备原子性" class="headerlink" title="lua脚本释放锁具备原子性"></a>lua脚本释放锁具备原子性</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">unlock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="comment">// 使用lua脚本进行原子删除操作</span></span><br><span class="line">      String checkAndDelScript = <span class="string">"if redis.call('get', KEYS[1]) == ARGV[1] then "</span> +</span><br><span class="line">                                  <span class="string">"return redis.call('del', KEYS[1]) "</span> +</span><br><span class="line">                                  <span class="string">"else "</span> +</span><br><span class="line">                                  <span class="string">"return 0 "</span> +</span><br><span class="line">                                  <span class="string">"end"</span>;</span><br><span class="line">      jedis.eval(checkAndDelScript, <span class="number">1</span>, lockKey, lockValue);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<h1 id="Redisson实现分布式锁"><a href="#Redisson实现分布式锁" class="headerlink" title="Redisson实现分布式锁"></a>Redisson实现分布式锁</h1><h2 id="Redisson原理"><a href="#Redisson原理" class="headerlink" title="Redisson原理"></a>Redisson原理</h2><p><img src="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/1090617-20190618183025891-1248337684.jpg" alt="img"></p>
<ol>
<li><p><strong>加锁机制</strong></p>
<p>线程去获取锁,获取成功:执行lua脚本,保存数据到redis数据库</p>
<p>线程去获取锁,获取失败:一直通过while循环尝试获取锁,获取成功后，执行lua脚本，保存数据到redis数据库</p>
</li>
<li><p><strong>watch dog自动延期机制</strong></p>
<p>它的作用就是 线程1 业务还没有执行完，锁时间就过了，线程1 还想持有锁的话，就会启动一个watch dog后台线程，不断的延长锁key的生存时间。</p>
</li>
<li><p><strong>LUA脚本</strong></p>
<p>主要是如果你的业务逻辑复杂的话，通过封装在lua脚本中发送给redis，而且redis是单线程的，这样就保证这段复杂业务逻辑执行的<strong>原子性</strong>。</p>
</li>
<li><p><strong>可重入锁</strong></p>
<p>Hash数据类型的key值包含了当前线程信息。</p>
<p>下面是redis存储的数据</p>
<p><img src="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/1090617-20190618183037704-975536201.png" alt="img"></p>
<p>这里表面数据类型是Hash类型,Hash类型相当于我们java的 <code>&lt;key,&lt;key1,value&gt;&gt;</code> 类型,这里key是指 ‘redisson’</p>
<p>它的有效期还有9秒，我们再来看里们的key1值为<code>078e44a3-5f95-4e24-b6aa-80684655a15a:45</code>它的组成是:</p>
<p>guid + 当前线程的ID。后面的value是就和可重入加锁有关。</p>
<p><strong>举图说明</strong></p>
<p><img src="https://jameslin23.gitee.io/2020/12/07/redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/1090617-20190618183046827-1994396879.png" alt="img"></p>
<p>上面这图的意思就是可重入锁的机制，它最大的优点就是相同线程不需要在等待锁，而是可以直接进行相应操作。</p>
</li>
</ol>
<h2 id="Redis分布式锁缺陷"><a href="#Redis分布式锁缺陷" class="headerlink" title="Redis分布式锁缺陷"></a>Redis分布式锁缺陷</h2><p><strong>Redis分布式锁会有个缺陷，就是在Redis哨兵模式下:</strong></p>
<p><code>客户端1</code> 对某个<code>master节点</code>写入了redisson锁，此时会异步复制给对应的 slave节点。但是这个过程中一旦发生 master节点宕机，主备切换，slave节点从变为了 master节点。</p>
<p>这时<code>客户端2</code> 来尝试加锁的时候，在新的master节点上也能加锁，此时就会导致多个客户端对同一个分布式锁完成了加锁。</p>
<p>这时系统在业务语义上一定会出现问题，<strong>导致各种脏数据的产生</strong>。</p>
<p><code>缺陷</code>在哨兵模式或者主从模式下，如果 master实例宕机的时候，可能导致多个客户端同时完成加锁。</p>
<h2 id="RLock接口"><a href="#RLock接口" class="headerlink" title="RLock接口"></a>RLock接口</h2><p><strong>Redisson分布式锁是基于RLock接口,RedissonLock实现RLock接口</strong>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">RLock</span> <span class="keyword">extends</span> <span class="title">Lock</span>, <span class="title">RExpirable</span>, <span class="title">RLockAsync</span></span></span><br></pre></td></tr></table></figure>

<p>很明显RLock是继承Lock锁,所以他有Lock锁的所有特征,比如lock,unlock,trylock等特征，同时它很多新特性:强制锁释放,带有效期的锁。</p>
<h2 id="RLock锁API"><a href="#RLock锁API" class="headerlink" title="RLock锁API"></a>RLock锁API</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">RLock</span> </span>&#123;</span><br><span class="line">    <span class="comment">//----------------------Lock接口方法-----------------------</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 加锁 锁的有效期默认30秒</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * tryLock()方法是有返回值的，它表示用来尝试获取锁，如果获取成功，则返回true，如果获取失败（即锁已被其他线程获取），则返回false .</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">tryLock</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * tryLock(long time, TimeUnit unit)方法和tryLock()方法是类似的，只不过区别在于这个方法在拿不到锁时会等待一定的时间，</span></span><br><span class="line"><span class="comment">     * 在时间期限之内如果还拿不到锁，就返回false。如果如果一开始拿到锁或者在等待期间内拿到了锁，则返回true。</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> time 等待时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> unit 时间单位 小时、分、秒、毫秒等</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">tryLock</span><span class="params">(<span class="keyword">long</span> time, TimeUnit unit)</span> <span class="keyword">throws</span> InterruptedException</span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 解锁</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">unlock</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 中断锁 表示该锁可以被中断 假如A和B同时调这个方法，A获取锁，B为获取锁，那么B线程可以通过</span></span><br><span class="line"><span class="comment">     * Thread.currentThread().interrupt(); 方法真正中断该线程</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">lockInterruptibly</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//----------------------RLock接口方法-----------------------</span></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 加锁 上面是默认30秒这里可以手动设置锁的有效时间</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> leaseTime 锁有效时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> unit      时间单位 小时、分、秒、毫秒等</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">lock</span><span class="params">(<span class="keyword">long</span> leaseTime, TimeUnit unit)</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 这里比上面多一个参数，多添加一个锁的有效时间</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> waitTime  等待时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> leaseTime 锁有效时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> unit      时间单位 小时、分、秒、毫秒等</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">tryLock</span><span class="params">(<span class="keyword">long</span> waitTime, <span class="keyword">long</span> leaseTime, TimeUnit unit)</span> <span class="keyword">throws</span> InterruptedException</span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 检验该锁是否被线程使用，如果被使用返回True</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isLocked</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 检查当前线程是否获得此锁（这个和上面的区别就是该方法可以判断是否当前线程获得此锁，而不是此锁是否被线程占有）</span></span><br><span class="line"><span class="comment">     * 这个比上面那个实用</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isHeldByCurrentThread</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 中断锁 和上面中断锁差不多，只是这里如果获得锁成功,添加锁的有效时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> leaseTime  锁有效时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> unit       时间单位 小时、分、秒、毫秒等</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">lockInterruptibly</span><span class="params">(<span class="keyword">long</span> leaseTime, TimeUnit unit)</span></span>;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="RedissonLock实现类"><a href="#RedissonLock实现类" class="headerlink" title="RedissonLock实现类"></a>RedissonLock实现类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedissonLock</span> <span class="keyword">extends</span> <span class="title">RedissonExpirable</span> <span class="keyword">implements</span> <span class="title">RLock</span></span></span><br></pre></td></tr></table></figure>

<h3 id="void-lock-方法"><a href="#void-lock-方法" class="headerlink" title="void lock()方法"></a>void lock()方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">lock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        lockInterruptibly();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        Thread.currentThread().interrupt();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>发现lock锁里面进去其实用的是lockInterruptibly(中断锁,表示可以被中断),而且捕获异常后用Thread.currentThread().interupt()来真正中断当前线程,其实它们是搭配一起使用的</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 1、带上默认值调另一个中断锁方法</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">lockInterruptibly</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">     lockInterruptibly(-<span class="number">1</span>, <span class="keyword">null</span>);</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 2、另一个中断锁的方法</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">lockInterruptibly</span><span class="params">(<span class="keyword">long</span> leaseTime, TimeUnit unit)</span> <span class="keyword">throws</span> InterruptedException </span></span><br><span class="line"><span class="function"> <span class="comment">/**</span></span></span><br><span class="line"><span class="function"><span class="comment">  * 3、这里已经设置了锁的有效时间默认为30秒  （commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout()=30）</span></span></span><br><span class="line"><span class="function"><span class="comment">  */</span></span></span><br><span class="line"><span class="function"> RFuture&lt;Long&gt; ttlRemainingFuture </span>= tryLockInnerAsync(commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);</span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 4、最后通过lua脚本访问Redis,保证操作的原子性</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> &lt;T&gt; <span class="function">RFuture&lt;T&gt; <span class="title">tryLockInnerAsync</span><span class="params">(<span class="keyword">long</span> leaseTime, TimeUnit unit, <span class="keyword">long</span> threadId, RedisStrictCommand&lt;T&gt; command)</span> </span>&#123;</span><br><span class="line">     internalLockLeaseTime = unit.toMillis(leaseTime);</span><br><span class="line"></span><br><span class="line">     <span class="keyword">return</span> commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command,</span><br><span class="line">             <span class="string">"if (redis.call('exists', KEYS[1]) == 0) then "</span> +</span><br><span class="line">                     <span class="string">"redis.call('hset', KEYS[1], ARGV[2], 1); "</span> +</span><br><span class="line">                     <span class="string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +</span><br><span class="line">                     <span class="string">"return nil; "</span> +</span><br><span class="line">                     <span class="string">"end; "</span> +</span><br><span class="line">                     <span class="string">"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then "</span> +</span><br><span class="line">                     <span class="string">"redis.call('hincrby', KEYS[1], ARGV[2], 1); "</span> +</span><br><span class="line">                     <span class="string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +</span><br><span class="line">                     <span class="string">"return nil; "</span> +</span><br><span class="line">                     <span class="string">"end; "</span> +</span><br><span class="line">                     <span class="string">"return redis.call('pttl', KEYS[1]);"</span>,</span><br><span class="line">             Collections.&lt;Object&gt;singletonList(getName()), internalLockLeaseTime, getLockName(threadId));</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h3 id="tryLock-long-waitTime-long-leaseTime-TimeUnit-unit"><a href="#tryLock-long-waitTime-long-leaseTime-TimeUnit-unit" class="headerlink" title="tryLock(long waitTime,long leaseTime,TimeUnit unit)"></a>tryLock(long waitTime,long leaseTime,TimeUnit unit)</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">tryLock</span><span class="params">(<span class="keyword">long</span> waitTime, <span class="keyword">long</span> leaseTime, TimeUnit unit)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">       <span class="keyword">long</span> time = unit.toMillis(waitTime);</span><br><span class="line">       <span class="keyword">long</span> current = System.currentTimeMillis();</span><br><span class="line">       <span class="keyword">long</span> threadId = Thread.currentThread().getId();</span><br><span class="line">       Long ttl = tryAcquire(leaseTime, unit, threadId);</span><br><span class="line">       <span class="comment">//1、 获取锁同时获取成功的情况下，和lock(...)方法是一样的 直接返回True，获取锁False再往下走</span></span><br><span class="line">       <span class="keyword">if</span> (ttl == <span class="keyword">null</span>) &#123;</span><br><span class="line">           <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="comment">//2、如果超过了尝试获取锁的等待时间,当然返回false 了。</span></span><br><span class="line">       time -= System.currentTimeMillis() - current;</span><br><span class="line">       <span class="keyword">if</span> (time &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">           acquireFailed(threadId);</span><br><span class="line">           <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="comment">// 3、订阅监听redis消息，并且创建RedissonLockEntry，其中RedissonLockEntry中比较关键的是一个 Semaphore属性对象,用来控制本地的锁请求的信号量同步，返回的是netty框架的Future实现。</span></span><br><span class="line">       <span class="keyword">final</span> RFuture&lt;RedissonLockEntry&gt; subscribeFuture = subscribe(threadId);</span><br><span class="line">       <span class="comment">//  阻塞等待subscribe的future的结果对象，如果subscribe方法调用超过了time，说明已经超过了客户端设置的最大wait time，则直接返回false，取消订阅，不再继续申请锁了。</span></span><br><span class="line">       <span class="comment">//  只有await返回true，才进入循环尝试获取锁</span></span><br><span class="line">       <span class="keyword">if</span> (!await(subscribeFuture, time, TimeUnit.MILLISECONDS)) &#123;</span><br><span class="line">           <span class="keyword">if</span> (!subscribeFuture.cancel(<span class="keyword">false</span>)) &#123;</span><br><span class="line">               subscribeFuture.addListener(<span class="keyword">new</span> FutureListener&lt;RedissonLockEntry&gt;() &#123;</span><br><span class="line">                   <span class="meta">@Override</span></span><br><span class="line">                   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">operationComplete</span><span class="params">(Future&lt;RedissonLockEntry&gt; future)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                       <span class="keyword">if</span> (subscribeFuture.isSuccess()) &#123;</span><br><span class="line">                           unsubscribe(subscribeFuture, threadId);</span><br><span class="line">                       &#125;</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;);</span><br><span class="line">           &#125;</span><br><span class="line">           acquireFailed(threadId);</span><br><span class="line">           <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">//4、如果没有超过尝试获取锁的等待时间，那么通过While一直获取锁。最终只会有两种结果</span></span><br><span class="line">       <span class="comment">//1)、在等待时间内获取锁成功 返回true。2）等待时间结束了还没有获取到锁那么返回false。</span></span><br><span class="line">       <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">           <span class="keyword">long</span> currentTime = System.currentTimeMillis();</span><br><span class="line">           ttl = tryAcquire(leaseTime, unit, threadId);</span><br><span class="line">           <span class="comment">// 获取锁成功</span></span><br><span class="line">           <span class="keyword">if</span> (ttl == <span class="keyword">null</span>) &#123;</span><br><span class="line">               <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">           &#125;</span><br><span class="line">          <span class="comment">//   获取锁失败</span></span><br><span class="line">           time -= System.currentTimeMillis() - currentTime;</span><br><span class="line">           <span class="keyword">if</span> (time &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">               acquireFailed(threadId);</span><br><span class="line">               <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>tryLock一般用于特定满足需求的场合,但不建议作为一般需求的分布式锁，一般分布式锁建议用void lock(long leaseTime,TimeUnit unit)。因此性能上考虑，在高并发情况下后者效率是前者的好几倍。</p>
<h3 id="unlock"><a href="#unlock" class="headerlink" title="unlock()"></a>unlock()</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">unlock</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 1.通过 Lua 脚本执行 Redis 命令释放锁</span></span><br><span class="line">        Boolean opStatus = commandExecutor.evalWrite(getName(), LongCodec.INSTANCE,</span><br><span class="line">                RedisCommands.EVAL_BOOLEAN,</span><br><span class="line">                <span class="string">"if (redis.call('exists', KEYS[1]) == 0) then "</span> +</span><br><span class="line">                        <span class="string">"redis.call('publish', KEYS[2], ARGV[1]); "</span> +</span><br><span class="line">                        <span class="string">"return 1; "</span> +</span><br><span class="line">                        <span class="string">"end;"</span> +</span><br><span class="line">                        <span class="string">"if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then "</span> +</span><br><span class="line">                        <span class="string">"return nil;"</span> +</span><br><span class="line">                        <span class="string">"end; "</span> +</span><br><span class="line">                        <span class="string">"local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); "</span> +</span><br><span class="line">                        <span class="string">"if (counter &gt; 0) then "</span> +</span><br><span class="line">                        <span class="string">"redis.call('pexpire', KEYS[1], ARGV[2]); "</span> +</span><br><span class="line">                        <span class="string">"return 0; "</span> +</span><br><span class="line">                        <span class="string">"else "</span> +</span><br><span class="line">                        <span class="string">"redis.call('del', KEYS[1]); "</span> +</span><br><span class="line">                        <span class="string">"redis.call('publish', KEYS[2], ARGV[1]); "</span> +</span><br><span class="line">                        <span class="string">"return 1; "</span>+</span><br><span class="line">                        <span class="string">"end; "</span> +</span><br><span class="line">                        <span class="string">"return nil;"</span>,</span><br><span class="line">                Arrays.&lt;Object&gt;asList(getName(), getChannelName()),</span><br><span class="line">                LockPubSub.unlockMessage, internalLockLeaseTime,</span><br><span class="line">                getLockName(Thread.currentThread().getId()));</span><br><span class="line">        <span class="comment">// 2.非锁的持有者释放锁时抛出异常</span></span><br><span class="line">        <span class="keyword">if</span> (opStatus == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalMonitorStateException(</span><br><span class="line">                    <span class="string">"attempt to unlock lock, not locked by current thread by node id: "</span></span><br><span class="line">                            + id + <span class="string">" thread-id: "</span> + Thread.currentThread().getId());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 3.释放锁后取消刷新锁失效时间的调度任务</span></span><br><span class="line">        <span class="keyword">if</span> (opStatus) &#123;</span><br><span class="line">            cancelExpirationRenewal();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>使用EVAL命令执行Lua脚本来释放锁:</p>
<ol>
<li>key 不存在,说明锁已经释放,直接执行<code>public</code>命令发布释放锁消息并返回1</li>
<li>key存在,但field在 Hash 中不存在，说明自己不是锁持有者，无权释放锁，返回 <code>nil</code>。</li>
<li>因为锁可重入,所以释放锁时不能把所有已获取的锁全部释放掉,一次只能释放一把锁,因此执行<code>hincrby</code>对锁的值减1。</li>
<li>释放一把锁后，如果还有剩余的锁,则刷新锁的失效时间并返回<code>0</code>；如果刚才释放的已经是最后一把锁，则执行 <code>del</code> 命令删除锁的 key，并发布锁释放消息，返回 <code>1</code>。</li>
</ol>
<p><code>注意</code>这里有个实际开发过程中，容易出现很容易出现上面第二步异常，非锁的持有者释放锁时抛出异常。比如下面这种情况</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//设置锁1秒过去</span></span><br><span class="line">      redissonLock.lock(<span class="string">"redisson"</span>, <span class="number">1</span>);</span><br><span class="line">      <span class="comment">/**</span></span><br><span class="line"><span class="comment">       * 业务逻辑需要咨询2秒</span></span><br><span class="line"><span class="comment">       */</span></span><br><span class="line">      redissonLock.release(<span class="string">"redisson"</span>);</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 线程1 进来获得锁后，线程一切正常并没有宕机，但它的业务逻辑需要执行2秒，这就会有个问题，在 线程1 执行1秒后，这个锁就自动过期了，</span></span><br><span class="line"><span class="comment">     * 那么这个时候 线程2 进来了。在线程1去解锁就会抛上面这个异常（因为解锁和当前锁已经不是同一线程了）</span></span><br><span class="line"><span class="comment">     */</span></span><br></pre></td></tr></table></figure>


      
    </div>
    <footer class="article-footer">
      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: '打赏支持', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: 'https://raw.githubusercontent.com/iTimeTraveler/iTimeTraveler.github.io/site/source/about/donate/images/WeChanQR.png',
  alipayImage: 'https://raw.githubusercontent.com/iTimeTraveler/iTimeTraveler.github.io/site/source/about/donate/images/AliPayQR.jpg'
});
</script>
      
      
      <div>
        <ul class="post-copyright">
          <li class="post-copyright-author">
          <strong>本文作者:  </strong>LeBron Tao
          </li>
          <li class="post-copyright-link">
          <strong>本文链接:  </strong>
          <a href="/2020/12/07/redis分布式锁/" target="_blank" title="redis分布式锁">https://jameslin23.gitee.io/2020/12/07/redis分布式锁/</a>
          </li>
          <li class="post-copyright-license">
            <strong>版权声明:   </strong>
            本博客所有文章除特别声明外，均采用 <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">CC BY-NC-ND 4.0</a>
            许可协议。转载请注明出处
          </li>
         
        </ul>
<div>
</div></div>
      
      
        
	<div id="comment">
		<!-- 来必力City版安装代码 -->
		<div id="lv-container" data-id="city" data-uid="MTAyMC8yOTQ4MS82MDQ5">
		<script type="text/javascript">
		   (function(d, s) {
		       var j, e = d.getElementsByTagName(s)[0];

		       if (typeof LivereTower === 'function') { return; }

		       j = d.createElement(s);
		       j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
		       j.async = true;

		       e.parentNode.insertBefore(j, e);
		   })(document, 'script');
		</script>
		<noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
		</div>
		<!-- City版安装代码已完成 -->
	</div>



      
      
        
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/缓存/">缓存</a></li></ul>

      

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/12/09/redis面试专题/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">
        
          redis面试专题
        
      </div>
    </a>
  
  
    <a href="/2020/12/07/redis缓存故障/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">redis缓存故障</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="toc-sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录</strong>
    
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#分布式锁"><span class="nav-number">1.</span> <span class="nav-text">分布式锁</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是分布式锁"><span class="nav-number">1.1.</span> <span class="nav-text">什么是分布式锁?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分布式锁需要具备哪些条件"><span class="nav-number">1.2.</span> <span class="nav-text">分布式锁需要具备哪些条件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分布式锁实现有哪些？"><span class="nav-number">1.3.</span> <span class="nav-text">分布式锁实现有哪些？</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分布式锁实现"><span class="nav-number">2.</span> <span class="nav-text">分布式锁实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#SET-key-value-NX"><span class="nav-number">2.1.</span> <span class="nav-text">SET key value NX</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SET-lockKey-value-NX-EX-30"><span class="nav-number">2.2.</span> <span class="nav-text">SET lockKey value NX EX 30</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#lua脚本释放锁具备原子性"><span class="nav-number">2.3.</span> <span class="nav-text">lua脚本释放锁具备原子性</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Redisson实现分布式锁"><span class="nav-number">3.</span> <span class="nav-text">Redisson实现分布式锁</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Redisson原理"><span class="nav-number">3.1.</span> <span class="nav-text">Redisson原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis分布式锁缺陷"><span class="nav-number">3.2.</span> <span class="nav-text">Redis分布式锁缺陷</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#RLock接口"><span class="nav-number">3.3.</span> <span class="nav-text">RLock接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#RLock锁API"><span class="nav-number">3.4.</span> <span class="nav-text">RLock锁API</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#RedissonLock实现类"><span class="nav-number">3.5.</span> <span class="nav-text">RedissonLock实现类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#void-lock-方法"><span class="nav-number">3.5.1.</span> <span class="nav-text">void lock()方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#tryLock-long-waitTime-long-leaseTime-TimeUnit-unit"><span class="nav-number">3.5.2.</span> <span class="nav-text">tryLock(long waitTime,long leaseTime,TimeUnit unit)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#unlock"><span class="nav-number">3.5.3.</span> <span class="nav-text">unlock()</span></a></li></ol></li></ol></li></ol>
    
    </div>
  </aside>

</section>
        
      </div>
      
      <footer id="footer">
  

  <div class="container">
      	<div class="row">
	      <p> Powered by <a href="http://hexo.io/" target="_blank">Hexo</a> and <a href="https://github.com/iTimeTraveler/hexo-theme-hiker" target="_blank">Hexo-theme-hiker</a> </p>
	      <p id="copyRightEn">Copyright &copy; 2013 - 2021 JAVA All Rights Reserved.</p>
	      
	      
    		<p class="busuanzi_uv">
				访客数 : <span id="busuanzi_value_site_uv"></span> |  
				访问量 : <span id="busuanzi_value_site_pv"></span>
		    </p>
  		   
		</div>

		
  </div>
</footer>


<!-- min height -->

<script>
    var wrapdiv = document.getElementById("wrap");
    var contentdiv = document.getElementById("content");
    var allheader = document.getElementById("allheader");

    wrapdiv.style.minHeight = document.body.offsetHeight + "px";
    if (allheader != null) {
      contentdiv.style.minHeight = document.body.offsetHeight - allheader.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    } else {
      contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    }
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>




  <script src="/js/dialog.js"></script>








	<div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h2 class="modal-title" id="myModalLabel">设置</h2>
      </div>
      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">


      <div class="modal-body">
          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" onclick="javascript:setFontSize();" aria-expanded="true" aria-controls="collapseOne">
              正文字号大小
            </a>
          </div>
          <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
          <div class="panel-body">
            您已调整页面字体大小
          </div>
        </div>
      


          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" onclick="javascript:setBackground();" aria-expanded="true" aria-controls="collapseTwo">
              夜间护眼模式
            </a>
        </div>
          <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
          <div class="panel-body">
            夜间模式已经开启，再次单击按钮即可关闭 
          </div>
        </div>

        <div>
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关 于&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
        </div>
         <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
          <div class="panel-body">
            JAVA
          </div>
          <div class="panel-body">
            Copyright © 2021 LeBron Tao All Rights Reserved.
          </div>
        </div>
      </div>


      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <div class="modal-footer">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      </div>
    </div>
  </div>
</div>
  
  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
  
    <a id="menu-switch"><i class="fa fa-bars fa-lg"></i></a>
  
</body>
</html>